package com.fms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fms.entity.SysUser;
import com.fms.entity.TaskDept;
import com.fms.exception.ServiceException;
import com.fms.mapper.SysUserMapper;
import com.fms.mapper.TaskDeptMapper;
import com.fms.result.ResultData;
import com.fms.dto.DeptAccess;
import com.fms.entity.SysDept;
import com.fms.service.MenuCheckService;
import com.fms.service.SysDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/dept")
@RequiredArgsConstructor
public class SysDeptController {

    private final SysDeptService sysDeptService;

    private final MenuCheckService menuCheckService;

    private final SysUserMapper sysUserMapper;

    private final TaskDeptMapper taskDeptMapper;

    //部门列表
    @GetMapping("/deptList")
    public ResultData getDeptList(){
        List<SysDept> sysDepts = sysDeptService.getDeptList();
        return ResultData.success(sysDepts);
    }

    //根据Id获取部门信息
    @GetMapping("/getDept/{id}")
    public ResultData getDeptById(@PathVariable("id") String id) {
        SysDept sysDept = sysDeptService.getSysDeptById(id);
        return ResultData.success(sysDept);
    }

    //删除部门
    @PostMapping("/deleteDept/{id}")
    @PreAuthorize("hasRole('管理员')")
    public ResultData deleteDeptById(@PathVariable("id") String id){
        List<SysUser> sysUsers = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>().eq(SysUser::getDeptId, id));
        TaskDept taskDept = taskDeptMapper.selectOne(new LambdaQueryWrapper<TaskDept>().eq(TaskDept::getDeptId, id));
        if((sysUsers==null||sysUsers.isEmpty()) && taskDept==null){
            sysDeptService.deleteDeptById(id);
            menuCheckService.deleteByDeptId(id);
            return ResultData.success("删除成功!");
        }else{
            throw new ServiceException("该角色当前存在与之关联的人员或任务，不能删除");
        }
    }

    //删除多个部门
    @PostMapping("/deleteDepts")
    @PreAuthorize("hasAnyRole('管理员')")
    public ResultData deleteDepts(@RequestBody DeptAccess[] deptAccess){
        for (DeptAccess dept: deptAccess){
            String id = dept.getId().toString();
            List<SysUser> sysUsers = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>().eq(SysUser::getDeptId, id));
            TaskDept taskDept = taskDeptMapper.selectOne(new LambdaQueryWrapper<TaskDept>().eq(TaskDept::getDeptId, id));
            if((sysUsers==null||sysUsers.isEmpty()) && taskDept==null){
                sysDeptService.deleteDeptById(id);
                menuCheckService.deleteByDeptId(id);
            }else{
                throw new ServiceException(dept.getDeptName()+"这个角色当前存在与之关联的人员或任务，不能删除");
            }
        }
        return ResultData.success("删除成功!");
    }
}
